/**
 * Created by guomin on 2017/5/31.
 */
var validator=require('validator');

var checkParams = require('../common/checkParams');
var jsonWrite = require('../conf/response');
var getData = require('../common/getData');
var Date = require('../common/dateFormat');
var sendSms = require('../common/sendSms');

var resMsg = function(code){
  switch (code){
    case 0: return "SUCCESS"; break;
    case -11: return "code验证失败，请检查密码及code生成规则是否正确"; break;
    case -12: return "手机号码格式错误"; break;
    case -13: return "同一手机号获取验证码间隔时间小于30s"; break;
    case -21: return "商户号错误"; break;
    case -22: return "商户号超过合同期限"; break;
    case -23: return "参数不完整"; break;
    case 201: return "服务端异常"; break;
    default: return "其它错误"; break;
  }
};

exports = module.exports ={
  sendMessage:function(req,res){
    var date = new Date();
    var params = req.body;
    console.log("客户端传入参数:________",params);
    checkParams.isDefined(params,["appId","content","mobile","code"]).then(function(){
      return checkParams.isParamsEmpty(params,["appId","content","mobile","code"]);
    }).then(function(){
      return checkParams.isMobile(params.mobile);
    }).then(function(){
      return checkParams.isRepeatedMobile(params.mobile);
    }).then(function(){
      return getData.getAppInfoByAppId(params.appId);
    }).then(function(data){
      return checkParams.isRightCode(params,data);
    // }).then(function(){
    //   return sendSms.sendSms(params);
    }).then(function(){
      jsonWrite(res,{"status":0,"msg":resMsg(0),"time":date.toLocaleString()});
    }).catch(function(err){
      if(err){
        var isInt=validator.isInt(err.toString());
        if(isInt){
          jsonWrite(res,{"status":err,"msg":resMsg(err,params),"time":date.toLocaleString()});
        }else{
          jsonWrite(res,{"status":201,"msg":resMsg(201),"time":date.toLocaleString()});
          throw err;
        }
      }
    })
  }
};